
package network.sslProxy;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import network.utils.ProxyConstants;

/**
 * Act as a tunnel between Https server and browser..
 * 
 * @author http://arunava.in
 * 
 */
class SSLProxyThread extends Thread {

	private InputStream in;

	private OutputStream out;

	SSLProxyThread(final InputStream in, final OutputStream out) {
		this.in = in;
		this.out = out;
	}

	public void run() {
		if (ProxyConstants.logLevel >= 1) {
			System.out.println(new Date()
					+ " SSLProxyThread :: Started :: Reading and Writing ....."
					+ currentThread());
		}

		final byte[] buffer = new byte[ProxyConstants.MAX_BUFFER];
		int numberRead = 0;

		try {
			while (true) {
				numberRead = in.read(buffer);
				if (numberRead == -1) {
					break;
				}
				if (numberRead > 0) {
					out.write(buffer, 0, numberRead);
					out.flush();
				}
			}
		} catch (final Exception e) {
			if (ProxyConstants.logLevel >= 1) {
				System.out.println(new Date()
						+ " SSLProxyThread :: Error can be ignored :: "
						+ currentThread() + e.toString());
			}

		} finally {
			try {
				in.close();
				out.close();
			} catch (final Exception e) {
			}
		}
		if (ProxyConstants.logLevel >= 1) {
			System.out.println(new Date() + " SSLProxyThread :: Finished "
					+ currentThread());
		}
	}

}
